<template>
	<view class="box">
		<!-- 选择会员 -->
		<view class="selectMember">
			<view class="member">
				<view @click="dialog = true">{{userName || '会员：'}}</view>
				<view style="position: relative;">{{start_date || '日期：'}}
					<picker mode="date" :start="start" :end="end"  @change="bindDateChange" style="position: absolute;left:0;top: 0;width: 100%;height: 100%;">
						<view class="date">{{start_date}}</view>
					</picker> 
				</view>
			</view>
			<view :class="['save',number == 2?'':'unlight']" @click="number == 2?save(1):false" v-if="selected != 1">保存</view>
			<view :class="['toSend',number == 2?'':'unlight']" @click="number == 2?save(3):false">生成评估</view>
		</view>
		
		<view class="screenModular">
			<view class="pageOne" v-if="number == 1">
				<view class="constitutionModular" v-for="(item,index) in questionnaire" :key="index">
					<image src="@/static/img/healthStatus/constitutionPin.png" class="constitutionImg" v-if="index == 0"></image>
					<image src="@/static/img/healthStatus/constitutionQiXu.png" class="constitutionImg" v-else-if="index == 1"></image>
					<image src="@/static/img/healthStatus/constitutionYang.png" class="constitutionImg" v-else-if="index == 2"></image>
					<image src="@/static/img/healthStatus/constitutionYin.png" class="constitutionImg" v-else-if="index == 3"></image>
					<image src="@/static/img/healthStatus/constitutionTan.png" class="constitutionImg" v-else-if="index == 4"></image>
					<image src="@/static/img/healthStatus/constitutionShi.png" class="constitutionImg" v-else-if="index == 5"></image>
					<image src="@/static/img/healthStatus/constitutionXue.png" class="constitutionImg" v-else-if="index == 6"></image>
					<image src="@/static/img/healthStatus/constitutionYu.png" class="constitutionImg" v-else-if="index == 7"></image>
					<image src="@/static/img/healthStatus/constitutionBing.png" class="constitutionImg" v-else-if="index == 8"></image>
					
					<view class="questionModular">
						<view class="single" v-for="(aitem,aindex) in item.adTopicsRepliesEntityList" :key="aindex">
							<view class="title">
								<text>{{aindex <= 8 ? '0'+(aindex+1) : aindex+1}}</text>
								<view>{{aitem.name}}</view>
							</view>
							<view class="answer">
								<text  v-for="(bitem,bindex) in aitem.adTopicsRepliesEntityList" :key="bindex" @click="answer(aitem,bitem)" :class="bitem.checked == true ? 'checked' : ''">{{bitem.value && bitem.value.substr(0,2)}}</text>
							</view>
						</view>
					</view>		
				</view>
				<view class="nextPage" @click="nextPage">下一页</view>
			</view>
			<view class="pageTwo" v-if="number == 2">
				<view class="constitutionModular">
					<view class="lookingFor">
						<image src="@/static/img/healthStatus/lookingFor@2x.png" class="constitutionImg"></image>
						<text @click="see">判断标准</text>
					</view>
					<view class="questionModular">
						<view class="question" v-for="(sitem,sindex) in lookAndSmellDetails" :key="sindex">
							<view class="title">
								<text>{{sindex <= 8 ? '0'+(sindex+1) : sindex+1}}</text>
								<view>{{sitem.name}}</view>
							</view>
							<view class="option">
								<view v-for="(ditem,dindex) in sitem.adTopicsRepliesEntityList" :key="dindex" @click="change(sitem,ditem)">
									<image src="@/static/img/select@2x.png" v-if="ditem.checked == false"></image>
									<image src="@/static/img/selected@2x.png" v-else></image>
									<text>{{ditem.value}}</text>
								</view>
							</view>
						</view>
					</view>					
				</view>
				
				<view class="constitutionModular">
					<image src="@/static/img/healthStatus/conversionScore@2x.png" class="conversionScore"></image>
					<view class="chart">
						<tr>
							<th>体质类型</th>
							<th>转化分数</th>
							<th>分数对应</th>
						</tr>
						<tr v-for="(item,index) in scroeResult" :key="index">
							<td>{{item.typeName}}</td>
							<td>{{item.score}}</td>
							<td>{{item.result}}</td>
						</tr>
					</view>
				</view>	
				<view class="nextPage" @click="number = 1">上一页</view>
			</view>
		</view>
		
		<member :dialog.sync="dialog"  @hidedialog="hidedialog" @chooseUser="chooseUser"></member>
		<reportImgType5 ref="reportImgType5" :info="info"></reportImgType5>
		<u-modal v-model="showPopup" :show-cancel-button="true" @confirm="showPopup = false" :content="showContent"></u-modal>
	</view>
</template>

<script>
	import reportImgType5 from '@/pages/quickly/healthStatus/reportImgType5.vue'
	import member  from '@/components/selectMember/selectMember.vue';
	export default{
		components:{member,reportImgType5},
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				start:'',
				end:currentDate,
				start_date:'',
				userName:'',
				dialog:false,
				constitutionArray:['平和质 ','痰湿质','气虚质','阳虚质 ','阴虚质','湿热质','血瘀质','气郁质','特禀质 '],
				info:{},
				number:1,
				questionnaire:{},
				lookAndSmellDetails: {},
				showPopup: false,
				showContent: '',
				scroeResult: [], //计算转换分结果
				data:{
					appUserTopicsEntities:[]
				}, //提交数据
				selected:''
			}
		},
		onLoad(options) {
			const _this = this;
			_this.selected = options.selected
			if(_this.selected == 1 || options.id){
				_this.$api.findByUserId(options.userId).then((res)=>{
					this.sex = res.data.result.sex
				})
			}
			this.findByTopicsTypeAxios().then(()=>{
				this.lookAndSmellQuestion().then(()=>{
					if(options.id){
						// 编辑回显
						_this.editId = options.id
						_this.userId = options.userId
						_this.$api.AppMentalHealthAssessmentDetails(options.id).then((res)=>{
							_this.userName = res.data.result.newAppMentalHealthAssessmentEntity.userName
							_this.start_date = res.data.result.newAppMentalHealthAssessmentEntity.fillFormDate
							_this.tid = res.data.result.newAppMentalHealthAssessmentEntity.tid
							const data = res.data.result.newUserTopicsEntities
							_this.questionnaire.map((a)=>{
								a.adTopicsRepliesEntityList.map((b)=>{
									b.adTopicsRepliesEntityList.map((c)=>{
										data.map((d)=>{
											if(b.id == d.titleId ){
												c.nid = d.id
												if(c.elections == d.userOption){
													c.checked = true
												}
											}
										})
									})
								})
							})
							data.map((a)=>{
								_this.lookAndSmellDetails.map((b)=>{
									if(b.id == a.titleId){
										b.nid = a.id
										b.adTopicsRepliesEntityList.map((c)=>{
											a.userOption && a.userOption.split(',').map((d)=>{
												if(d == c.elections){
													c.checked = true
												}
											})
										})
									}
									
								})
							})
						})
					}
				})
			});
		},
		methods:{
			//判断是否有未选择答案的问题
			determine() {
				// this.questionnaire.map((a)=>{
				// 	a.adTopicsRepliesEntityList.map((b)=>{
				// 		b.adTopicsRepliesEntityList[parseInt(4*Math.random())].checked = true
				// 	})
				// })
				const aresult = this.questionnaire && this.questionnaire.map((a) => {
					const bresult = a.adTopicsRepliesEntityList.map((b) => {
						const cresult = b.adTopicsRepliesEntityList.filter((c) => {
							return c.checked
						})	
						return b.bresult = cresult
					})			
					return a
				})
				var noSelected = []
				const dArr = aresult.map((d)=>{
					var fArr = d.adTopicsRepliesEntityList.filter((f) => {
						if(f.bresult.length <= 0) {
							f.headline = d.adTopicsEntity.name;
							noSelected.push(f)
						}
						return f
					})
					
					return d
				})
				if(noSelected.length > 0) {
					this.showPopup = true,
					this.showContent = '请选择'+noSelected[0].headline +'下的'+noSelected[0].name
					return 
				}
				this.data.appUserTopicsEntities = []
				this.questionnaire.map((a)=>{
					a.adTopicsRepliesEntityList.map((b)=>{
						b.adTopicsRepliesEntityList.map((c)=>{
							if(c.checked){
								this.data.appUserTopicsEntities.push({
									userNumber:Number(c.numbers),
									userOption:c.elections,
									userValue:c.value,
									type:b.type,
									titleId:b.id,
									id:c.nid
								})
							}
						})
					})
				})
				this.data.healthId = JSON.parse(localStorage.userInfo).id
				this.data.source = 3
				this.data.userId = this.userId
				this.data.userName = this.userName
				this.data.tid = [30,31,32,33,34,35,36,37,38]
				this.$api.AppMentalHealthAssessmentRefresh(this.data).then((res)=>{
					if(res.data.returnCode == 200){
						this.scroeResult = res.data.result
						this.number = this.number + 1;
					}
				})
			},
			//选答案
			answer(aitem,bitem) {
				const answerArr = aitem.adTopicsRepliesEntityList.map((a) => {
					a.checked = false;
					return a
				})
				bitem.checked = true;
			},
			//望闻切选择
			change(sitem,ditem) {
				ditem.checked = !ditem.checked
			},
			save(e) {
				const _this = this;
				if(!this.userId) {
					uni.showToast({
						title:'请选择会员',
						icon:'none'
					})
					return
				}
				if(!this.start_date) {
					uni.showToast({
						title:'请选择日期',
						icon:'none'
					})
					return
				}
				this.lookAndSmellDetails.map((a,ai)=>{
					const bchecked = a.adTopicsRepliesEntityList.filter((b)=>{
						return b.checked
					})
					this.data.appUserTopicsEntities.push({
						userOption:bchecked.length > 0?bchecked.map((a)=>{return a.elections}).join(','):'',
						userValue:bchecked.length > 0?bchecked.map((a)=>{return a.value}).join(','):'',
						type:a.type,
						titleId:a.id,
						id:a.nid 
					})
				})
				this.data.status = e
				this.data.tid.push(39)
				this.data.upload = 7
				this.data.fillFormDate = this.start_date
				if(this.editId){
					if(this.selected == 1){
						delete this.data.source
					}
					// 编辑保存
					this.data.id = Number(this.editId)
					this.data.userId = Number(this.userId)
					this.data.appUserTopicsTitleEntity = { id : this.tid }
					this.$api.AppMentalHealthAssessmentUpdate(this.data).then((res)=>{
						if(res.data.returnCode == 200){
							if(e == 3){
								this.info = res.data.result
								uni.showLoading({title:'加载中'})
								setTimeout(()=>{
									_this.$refs.reportImgType5.toImg().then((base64)=>{
										var arr = base64.split(',')
										var mime = arr[0].match(/:(.*?);/)[1]
										var bstr = atob(arr[1]) 
										var nn = bstr.length 
										var u8arr = new Uint8Array(nn);
										while(nn--){
											u8arr[nn] = bstr.charCodeAt(nn);
										}
										var obj1 = new Blob([u8arr], {type:mime});
										_this.$api.healthAssessmentuploadWord({fileOne:obj1},res.data.result.id).then((ares) => {
											uni.hideLoading()
											if(JSON.parse(ares.data).returnCode == 200){
												window.location.href = 'http://health.jlm12580.com/web/viewer.html?file='+JSON.parse(ares.data).result.url
											}
										})
									})
								},1000)
							}else{
								uni.navigateTo({
									url:'/pages/quickly/healthStatus/navigation?current=6'
								})
							}
						}
					})
				}else{
					this.$api.AppMentalHealthAssessmentAdd(this.data).then((res)=>{
						if(res.data.returnCode == 200){
							if(e == 3){
								this.info = res.data.result
								uni.showLoading({title:'加载中'})
								setTimeout(()=>{
									_this.$refs.reportImgType5.toImg().then((base64)=>{
										var arr = base64.split(',')
										var mime = arr[0].match(/:(.*?);/)[1]
										var bstr = atob(arr[1]) 
										var nn = bstr.length 
										var u8arr = new Uint8Array(nn);
										while(nn--){
											u8arr[nn] = bstr.charCodeAt(nn);
										}
										var obj1 = new Blob([u8arr], {type:mime});
										_this.$api.healthAssessmentuploadWord({fileOne:obj1},res.data.result.id).then((ares) => {
											uni.hideLoading()
											if(JSON.parse(ares.data).returnCode == 200){
												window.location.href = 'http://health.jlm12580.com/web/viewer.html?file='+JSON.parse(ares.data).result.url
											}
										})
									})
								},1000)
							}else{
								uni.navigateTo({
									url:'/pages/quickly/healthStatus/navigation?current=6'
								})
							}
						}
					})
				}
			},
			// 获取题目
			findByTopicsTypeAxios(){
				return new Promise((success,error)=>{
					this.$api.findByTopicsType('ids=30&ids=31&ids=32&ids=33&ids=34&ids=35&ids=36&ids=37&ids=38').then((res)=>{
						if(res){
							const data =  Object.keys(res.data.result).map((a)=>{
								const aData =  res.data.result[a].adTopicsRepliesEntityList.map((b)=>{
									b.adTopicsRepliesEntityList.map((c)=>{c.checked = false;return b})
									return b
								})
								return res.data.result[a]
							})
							this.sex ?
								this.sex == 2 ? data[5].adTopicsRepliesEntityList.splice(6,1) : data[5].adTopicsRepliesEntityList.splice(5,1)
							:
								''
							this.questionnaire = data;
							success(res.data.result)
						}else{
							error('')
						}
					})
				})
			},
			// 望闻切题目
			lookAndSmellQuestion() {
				return new Promise((success,error) => {
					this.$api.findByTopicsType('ids=39').then((res) => {
						if(res) {
							this.lookAndSmellDetails = res.data.result[39] && res.data.result[39].adTopicsRepliesEntityList.map((a) => {
								a.adTopicsRepliesEntityList.map((b) => {
									return b.checked = false
								})
								return a
							});
							success(res.data.result)
						}else {
							error('')
						}
					})
				})
			},
			//下一页
			nextPage() {
				this.determine()
			},
			//判定标准
			see() {
				uni.navigateTo({
					url:'/pages/quickly/healthStatus/chineseMedicine/criteria'
				})
			},
			//关闭弹出框
			hidedialog(){
				this.dialog = false
			},
			//选择会员
			chooseUser(e){
				this.sex = e.sex
				this.userId = e.userId;
				this.userName = e.userName;
				e.sex == 2 ? this.questionnaire[5].adTopicsRepliesEntityList.splice(6,1) : this.questionnaire[5].adTopicsRepliesEntityList.splice(5,1);
			},
			// 日期
			bindDateChange(e) { 
				this.start_date = e.target.value;
			},
			// 获取当前时间
			getDate(type) {
			   const date = new Date();
			   let year = date.getFullYear();
			   let month = date.getMonth() + 1;
			   let day = date.getDate();
			  
			   if (type === 'start') {
				year = year - 60;
			   } else if (type === 'end') {
				year = year + 2;
			   }
			   month = month > 9 ? month : '0' + month;;
			   day = day > 9 ? day : '0' + day;
			   return `${year}-${month}-${day}`;
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/css/quickly/healthStatus/common.scss';
	.constitutionModular {
		margin-top: 28upx;
		.lookingFor {
			position: relative;
			text {
				position: absolute;
				right: 0;
				top: 50%;
				transform: translateY(-50%);
				color: #05C6AD;
				font-size: 28upx;
			}
		}
		.constitutionImg,.conversionScore {
			width: 336upx;
			height: 48upx;
			display: table;
			margin: auto;
		}
		.conversionScore {
			width: 264upx;
			height: 38upx;
			margin: 35upx auto;
		}
		.questionModular {
			width: 702upx;
			background: #FFFFFF;
			border-radius: 14upx;
			margin-top: 25upx;
			padding: 27upx 20upx 0;
			box-sizing: border-box;
			.single,.question {
				margin-top: 34upx;
				padding: 0 0 40upx;
				border-bottom: 1upx solid #DADADA;
				.title {
					display: flex;
					color: #333333;
					font-size: 30upx;
					text {
						width: 40upx;
						height: 26upx;
						line-height: 26upx;
						background: #05C6AD;
						border-radius: 14upx;
						color: #FFFFFF;
						font-size: 26upx;
						display: inline-block;
						text-align: center;
						margin-right: 18upx;
						margin-top: 6upx;
					}
					view {
						flex: 1;
					}
				}
				.answer {
					display: flex;
					align-items: center;
					padding: 40upx 0;
					border-bottom: 1upx solid #EBEBEB;
					text {
						color: #333333;
						font-size: 30upx;
						margin-right: 53upx;
						width: 45px;
						height: 44upx;
						border: 1upx solid #C5DFDB;
						border-radius: 22upx;
						text-align: center;
					}
					text:last-child{
						margin-right: 0;
					}
					.checked {
						background-color: #05C6AD;
						color: #FFFFFF;
						border: none;
					}
				}
				.option {
					display: flex;			
					flex-wrap: wrap;
					view {
						width: 33.3%;
						display: flex;
						align-items: center;
						margin-top: 20upx;
						image {
							width: 26upx;
							height: 26upx;
							margin-right: 12upx;
						}
					}
				}
			}
			.single {
				border: none;
				margin: 0;
			}
			.single:nth-child(1),
			.question:nth-child(1){
				margin: 0;
			}
			.question:last-child {
				border: none;
			}
			.single:last-child{
				.answer {
					border: none;
					padding-bottom: 10upx;
				}
			}
		}
		.chart {
			width: 702upx;
			border: 1upx solid #CEE1DF;
			background: #FFFFFF;
			border-radius: 14upx;
			tr {
				display: flex;
				border-bottom: 1upx solid #CEE1DF;
				th {
					flex: 1;
					color: #333333;
					font-size: 30upx;
					height: 84upx;
					text-align: center;
					line-height: 84upx;
					border-right: 1upx solid #CEE1DF;
				}
				th:last-child,td:last-child {
					border: none;
				}
				td {
					height: 64upx;
					flex: 1;
					text-align: center;
					line-height: 64upx;
					border-right: 1upx solid #CEE1DF;
					color: #333333;
					font-size: 30upx;
				}
			}
			tr:last-child {
				border: none;
			}
		}
	}
	.constitutionModular:nth-child(1) {
		margin-top: 0;
	}
	.nextPage {
		width: 392upx;
		height: 70upx;
		background: #05C6AD;
		box-shadow: 0 6upx 18upx 0px rgba(0, 226, 197, 0.35);
		border-radius: 35upx;
		color: #FFFFFF;
		font-size: 30upx;
		line-height: 70upx;
		text-align: center;
		display: table;
		margin: 83upx auto 70upx;
	}
	.unlight{
		background: #ccc !important;
		color: #333 !important;
	}
</style>
